#!/bin/bash

# 显示使用说明的函数
show_usage() {
    echo "Usage: $0 [options]"
    echo "Options:"
    echo "  -hn, --hostname HOSTNAME   Set new hostname"
    echo "  -i, --interface INTERFACE Set network interface (e.g., eth0, ens33)"
    echo "  -ip, --ip_address IP_ADDRESS Set new IP address (e.g., 192.168.1.100/24)"
    exit 1
}
# 如果参数个数为0，显示使用说明并退出
if [ "$#" -eq 0 ]; then
    show_usage
fi

# 设置默认参数值
NEW_HOSTNAME="template"
INTERFACE="ens33"
NEW_IP_ADDRESS="192.168.1.99/24"

# 解析命令行参数
while [ "$#" -gt 0 ]; do
    case "$1" in
        -hn|--hostname)
            NEW_HOSTNAME="$2"
            shift 2
            ;;
        -i|--interface)
            INTERFACE="$2"
            shift 2
            ;;
        -ip|--ip_address)
            NEW_IP_ADDRESS="$2"
            shift 2
            ;;
        *)
            show_usage            
            ;;
    esac
done

# 修改主机名
if [ -n "$NEW_HOSTNAME" ]; then
    echo "Changing hostname to $NEW_HOSTNAME"
    sudo hostnamectl set-hostname "$NEW_HOSTNAME"
fi

# 修改IP地址
if [ -n "$INTERFACE" ] && [ -n "$NEW_IP_ADDRESS" ]; then
    echo "Changing IP address for $INTERFACE to $NEW_IP_address"
	sudo nmcli connection modify $INTERFACE ipv4.addresses $NEW_IP_ADDRESS/24 ipv4.method "manual"
    sudo nmcli connection up $INTERFACE
fi

echo "Hostname and IP address changed successfully."